package com.hongxun.design.utils.fileutil;

import android.content.Context;
import android.os.Environment;
import android.os.Handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hongxun.design.MyApp;
import com.hongxun.design.bean.BackPhoto_Bean;
import com.hongxun.design.bean.CategoryItemBean;
import com.hongxun.design.bean.EncyclopediaBean;
import com.hongxun.design.bean.ExperienceBean;
import com.hongxun.design.bean.ProjectItemBean;
import com.hongxun.design.bean.SearchProjectBean;
import com.hongxun.design.bean.UserBean;
import com.hongxun.design.mytools.MString;
import com.hongxun.design.mytools.MyLog;
import com.hongxun.design.mytools.ShardPreferencesTool;
import com.hongxun.design.object_properties.MyMessage;
import com.hongxun.design.utils.FragmentUtil;
import com.hongxun.design.utils.fastjson.FastJsonUtil;
import com.hongxun.design.utils.httputil.HttpStringUtil;
import com.hongxun.design.utils.pathutil.ClipPathUtil;
import com.hongxun.design.utils.projectdatautil.DataFactory;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by zerdoor_pc on 2016/6/16.
 * 文件读写
 */
public class FileUtil {
    static FileUtil instence;
    Context mContext;

    FileUtil(Context mContext) {
        this.mContext = mContext;
    }

    public static FileUtil getInstence(Context m) {
        if (instence == null) {
            instence = new FileUtil(m);
        }
        return instence;
    }

    public String getCachaVoicePath() {
        String PATH = getCachaPath() + "Voice" + File.separator;
        File file = new File(PATH);
        if (!file.exists()) {
            file.mkdirs();
        }
        return PATH;
    }

    public String getCachaProVoicePath() {
        String PATH = getCachaPath() + MString.Project_ + MString.getValueId(MyApp.currProject.getStage_id(), MyApp.currProject.getUUID()) + File.separator + "Voice" + File.separator;
        File file = new File(PATH);
        if (!file.exists()) {
            file.mkdirs();
        }
        return PATH;
    }

    public String getCachaProVoiceRequestPath() {
        String PATH = getCachaRequestPath() + MString.Project_ + MString.getValueId(MyApp.currProject.getStage_id(), MyApp.currProject.getUUID()) + File.separator + "Voice" + File.separator;
        File file = new File(PATH);
        if (!file.exists()) {
            file.mkdirs();
        }
        return PATH;
    }

    public String getCachaPath() {
        String PATH = mContext.getFilesDir().getPath() + File.separator + MyApp.openIdent + File.separator;
        return PATH;
    }

    public String getCachaRequestPath() {
        String PATH = getCachaPath() + MString.Request + File.separator;
        return PATH;
    }

    public String getCachaPhotoPath() {
        String PATH = getCachaPath() + MString.Project_ + SetFileUtil.CheckStageId_type()
                + File.separator + MString.ExplorePointBelongFile + "_" + SetFileUtil.CheckExplorationId() + File.separator + "Photo/";
        return PATH;
    }

    //项目照片文件1
    public String getCachaPhotoPath_Record() {
        String PATH = getCachaPath() + MString.Project_
                + SetFileUtil.CheckStageId_type() + "/" + MString.ProjectRecord
                + "/Photo_" + SetFileUtil.CheckStageId_type();
        File file = new File(PATH);
        if (!file.exists()) {
            file.mkdirs();
        }
        return PATH;
    }

    //项目照片文件1
    public String getCachaPhotoPath_YH() {
        String PATH = getCachaPath() + MString.Project_
                + SetFileUtil.CheckStageId_type() + "/" + MString.projectYhJL
                + "/Photo_" + SetFileUtil.CheckStageId_type();
        File file = new File(PATH);
        if (!file.exists()) {
            file.mkdirs();
        }
        return PATH;
    }

    public String getCachaPhotoUuidPath() {
        String PATH = getCachaPath() + MString.Project_ + SetFileUtil.CheckStageId_type()
                + File.separator + MString.ExplorePointBelongFile + "_" + MyApp.currExploration.getUuid() + File.separator + "Photo/";

        return PATH;
    }

    public String getCachaPhotoRequestPath() {
        String PATH = getCachaPath() + MString.Request + File.separator + MString.Project_ + SetFileUtil.CheckStageId_type()
                + File.separator + MString.ExplorePointBelongFile + "_" + SetFileUtil.CheckExplorationId() + File.separator + "Photo/";

        return PATH;
    }

    public String getCachaPhotoVoicePath() {
        String PATH = getCachaPath() + MString.Project_ + SetFileUtil.CheckStageId_type()
                + File.separator;
        if (SetFileUtil.CheckExplorationId().length() > 0) {
            PATH += MString.ExplorePointBelongFile + "_" + SetFileUtil.CheckExplorationId() + File.separator;
        }

        return PATH + "Voice/";
    }

    public String getCachaPhotoVoiceRequestPath() {
        String PATH = getCachaPath() + MString.Request + File.separator + MString.Project_ + SetFileUtil.CheckStageId_type()
                + File.separator + MString.ExplorePointBelongFile + "_" + SetFileUtil.CheckExplorationId() + File.separator + "Voice/";
        return PATH;
    }

    public String getProRequestPath(String id) {
        String PATH = getCachaPath() + MString.Request + File.separator +
                MString.Project_ + id;

        return PATH;
    }

    public String getProPath(String id) {
        String PATH = getCachaPath() + MString.Project_ + id;
        return PATH;
    }


    /**
     * 以下为读取或写入方法*
     */
    /**
     * 写入系统*
     */
    public void SaveFileData(String name, String Data) {
        fileWrite(getJsonFileName(name), Data);
    }

    public void createFile(String dirs) {
        String PATH = mContext.getFilesDir().getPath() + "/" + MyApp.openIdent;
        File file = new File(PATH + File.separator + dirs);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    /**
     * 缓存入口*
     */
    public void SaveFileData(String dir, String name, String Data, String type) {
        //String PATH = ClipPathUtil.getAPPPath();
        //fileWriteToSD(PATH + MyApp.openIdent, name + ".json", Data);
        //dir为项目文件夹名字
        //name为项目文件名字
        //Data为项目文件内容

        /**防止在线时无缓存更新数据**/
        String PATH = mContext.getFilesDir().getPath() + "/" + MyApp.openIdent;

        File file = new File(PATH + File.separator + MString.Project_ + dir);
        if (!file.exists()) {
            file.mkdirs();
        }

        fileWrite(PATH, MString.Project_ + dir, name, Data);
        if (!MyApp.isOnLine && !type.equals("no")) {
            PATH += File.separator + MString.Request;
            checkLinePath();
            fileWrite(PATH, MString.Project_ + dir, name, Data);
            DataFactory.setUpdate(true);
        }

        //MyLog.L(MString.SUCCESSED + "存储：" +  PATH+name);
    }

    public void SaveFileDataAll(String dir, String name, String Data, String type) {
        //String PATH = ClipPathUtil.getAPPPath();
        //fileWriteToSD(PATH + MyApp.openIdent, name + ".json", Data);
        //dir为项目文件夹名字
        //name为项目文件名字
        //Data为项目文件内容

        /**防止在线时无缓存更新数据**/
        String PATH = mContext.getFilesDir().getPath() + "/" + MyApp.openIdent;

        File file = new File(PATH + File.separator + MString.Project_ + dir);
        if (!file.exists()) {
            file.mkdirs();
        }

        fileWrite(PATH, MString.Project_ + dir, name, Data);
        if (!type.equals("no")) {
            PATH += File.separator + MString.Request;
            checkLinePath();
            fileWrite(PATH, MString.Project_ + dir, name, Data);
            DataFactory.setUpdate(true);
        }

        //MyLog.L(MString.SUCCESSED + "存储：" +  PATH+name);
    }

    //存储随手拍记录、照片数据

    /**
     * dir为项目文件夹名字
     * name为项目文件名字
     * Data为项目文件内容
     */
    public void SaveFileDataAll(String dir, String name, String Data) {
        String PATH = mContext.getFilesDir().getPath() + "/" + MyApp.openIdent;
        File file = new File(PATH + File.separator + MString.Project_ + dir);
        if (!file.exists()) {
            file.mkdirs();
        }
        String dirname = MString.Project_ + dir;
        fileWrite(PATH, dirname, name, Data);
    }

    public void SaveFileRequestData(String dir, String name, String Data, String type) {

        if (!MyApp.isOnLine) {
            /**防止在线时无缓存更新数据**/
            String PATH = mContext.getFilesDir().getPath() + "/" + MyApp.openIdent;
            File file1 = new File(PATH + File.separator + MString.Request);
            if (!file1.exists()) {
                file1.mkdirs();
            }
            File file = new File(PATH + File.separator + dir);
            if (!file.exists()) {
                file.mkdirs();
            }
            fileWrite(PATH, dir, name, Data);
            DataFactory.setUpdate(true);

        }
    }

    /**
     * 同步*
     */
    public void SaveFileDataLine(String dir, String name, String Data, String type) {

        String PATH = mContext.getFilesDir().getPath() + "/" + MyApp.openIdent;
        checkLinePath();
        File file = new File(PATH + File.separator + MString.Request + File.separator + MString.Project_ + dir);
        if (!file.exists()) {
            return;
        }
        fileWrite(PATH, MString.Project_ + dir, name, Data);
        //MyLog.L(MString.SUCCESSED + "存储：" +  PATH+name);
    }

    private void checkLinePath() {
        String PATH = mContext.getFilesDir().getPath() + File.separator + MyApp.openIdent + File.separator + MString.Request;
        File file = new File(PATH);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    /**
     * 缓存入口(踏勘点文件夹)*
     */
    public void SaveFileData(String dir, String dir2, String name, String Data, String type) {
        /**防止在线时无缓存更新数据**/
        String PATH = mContext.getFilesDir().getPath() + "/" + MyApp.openIdent;
        File file = new File(PATH + File.separator + MString.Project_ + dir);
        if (!file.exists()) {
            return;
        }

        fileWrite(PATH + File.separator + MString.Project_ + dir, dir2, name, Data);
        //MyLog.L(MString.SUCCESSED + "存储：" +  PATH+name);
    }

    /**
     * 缓存入口(踏勘点文件夹创建)*
     */
    public void SaveFileData(String dir, String pointdir, String... s) {
        /**防止在线时无缓存更新数据**/
        String PATH = mContext.getFilesDir().getPath() + "/" + MyApp.openIdent;
        PATH += File.separator + dir;
        File file = new File(PATH);
        if (!file.exists()) {
            return;
        }
        PATH += File.separator + pointdir;
        File file2 = new File(PATH);
        if (!file2.exists()) {
            file2.mkdirs();
        }

        if (s != null && s.length > 0) {
            for (int i = 0; i < s.length; i++) {
                if (s[i].equals("Voice")) {
                    File file3 = new File(PATH + File.separator + s[i]);
                    if (!file3.exists()) {
                        file3.mkdirs();
                    }
                } else {
                    File file3 = new File(PATH + File.separator + "Photo/" + s[i]);
                    if (!file3.exists()) {
                        file3.mkdirs();
                    }

                }

            }
        }
    }

    public void SaveFileData(String name, String Data, String type) {
        //name为项目文件名字
        //Data为项目文件内容
        String PATH = mContext.getFilesDir().getPath() + File.separator;
        fileWrite(PATH + MyApp.openIdent, name, Data);
        //MyLog.L(MString.SUCCESSED + "存储：" +  PATH+name);
    }


    /**
     * 读取缓存json*
     */
    public void ReadFileToSend(Handler handler, String name) {
        String BaseJson = MyApp.File.ReadFileData(MString.Project_ + MyApp.currProject.getStage_id() + File.separator + name);
        if (BaseJson != null && BaseJson.length() > 0) {
            handler.sendMessage(MyMessage.getMessage(HttpStringUtil.SUCCESSED, BaseJson));
        }
    }

    public void ReadFileToSend(Handler handler, String name, String no) {
        String BaseJson = MyApp.File.ReadFileData(name);
        if (BaseJson != null && BaseJson.length() > 0) {
            handler.sendMessage(MyMessage.getMessage(HttpStringUtil.SUCCESSED, BaseJson));
        }
    }


    public String ReadFileData(String path) {
        String PATH = mContext.getFilesDir().getPath() + File.separator + MyApp.openIdent;
        if (!PATH.endsWith(File.separator)) {
            PATH = PATH + File.separator;
        }

        return Read(PATH + path);
    }

    /**
     * 写入系统*
     */
    private void fileWrite(String filename, String Content) {
        FileOutputStream out = null;
        try {
            out = mContext.openFileOutput(filename, Context.MODE_PRIVATE);
            out.write(Content.getBytes("UTF-8"));
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 写入系统*
     */
    private void fileWrite(String path, String dirname, String filename, String Content) {
        FileOutputStream out = null;

        try {
            File parent = new File(path);
            if (!parent.exists()) {
                parent.mkdirs();
            }
            File file = new File(path + File.separator + dirname);

            if (!file.exists()) {
                file.mkdirs();
            }

            saveToSDCard(path + File.separator + dirname + File.separator + filename, Content);
//            out = mContext.openFileOutput(filename, Context.MODE_PRIVATE);
//            out.write(Content.getBytes("UTF-8"));
//            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void fileWrite(String path, String filename, String Content) {
        FileOutputStream out = null;

        try {
            File parent = new File(path);
            if (!parent.exists()) {
                parent.mkdirs();
            }

            saveToSDCard(path + File.separator + filename, Content);
//            out = mContext.openFileOutput(filename, Context.MODE_PRIVATE);
//            out.write(Content.getBytes("UTF-8"));
//            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 写入SD卡*
     */
    private void fileWriteToSD(String path, String filename, String Content) {
        try {
            MyLog.L(MString.SUCCESSED + "存储：path=" + path);
            File parent = new File(path);
            if (!parent.exists()) {
                parent.mkdirs();
            }
            //判断SDcard是否存在并且可读写
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {

                saveToSDCard(path + "/" + filename, Content);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 读取*
     */
    private String fileRead(String filename) {
        FileInputStream in = null;
        ByteArrayOutputStream bout = null;
        byte[] buf = new byte[1024];
        bout = new ByteArrayOutputStream();
        int length = 0;
        try {
            in = mContext.openFileInput(filename); //获得输入流
            while ((length = in.read(buf)) != -1) {
                bout.write(buf, 0, length);
            }
            byte[] content = bout.toByteArray();
            return new String(content, "UTF-8"); //设置文本框为读取的内容
        } catch (Exception e) {
            try {
                in.close();
                bout.close();
            } catch (Exception x) {

            }
            return "";
        }
    }

    /**
     * 读取*
     */
    public String Read(String path) {
        MyLog.L(MString.SUCCESSED + " 读取path=" + path);
        File temp = null;
        FileInputStream input = null;
        ByteArrayOutputStream bout = null;
        try {
            temp = new File(path);
            input = new FileInputStream(temp);
            byte[] b = new byte[1024 * 5];
            int len;


            bout = new ByteArrayOutputStream();
            while ((len = input.read(b)) != -1) {
                bout.write(b, 0, len);
            }
            byte[] content = bout.toByteArray();
            try {
                bout.close();
                input.close();
            } catch (Exception x) {

            }
            MyLog.L(MString.SUCCESSED + " 读取path成功：" + new String(content, "UTF-8"));
            return new String(content, "UTF-8"); //设置文本框为读取的内容
        } catch (Exception e) {
            MyLog.L(MString.SUCCESSED + " 读取path异常：" + e.getMessage());
            try {
                bout.close();
                input.close();
            } catch (Exception x) {
                MyLog.L(MString.SUCCESSED + " 读取path异常2：" + x.getMessage());
            }
            return "";
        }


    }


    /**
     * 保存到path
     *
     * @param filename
     * @param filecontent
     * @throws Exception
     */
    public void saveToSDCard(String filename, String filecontent) throws Exception {
        MyLog.L(MString.SUCCESSED + "存储：filename=" + filename);
        MyLog.L(MString.SUCCESSED + "存储：filecontent=" + filecontent);
        java.io.File file = new File(filename);
        if (!file.exists()) {
            file.createNewFile();
        }
        FileOutputStream outStream = new FileOutputStream(file);
//        outStream.write(filecontent.getBytes());
        outStream.write(filecontent.getBytes("UTF-8"));
        outStream.close();
    }


    /**
     * 文件存储命名
     */
    private String getJsonFileName(String File) {
        // MyLog.L(MString.SUCCESSED+" SUCCESSEDFilename="+File+ MyApp.openIdent + ".json");
        return File + MyApp.openIdent + ".json";
    }


    /**
     * 复制缓存文件夹*
     */
    public void copyDir() {//String from,String to
        copyFolder(mContext.getFilesDir().getPath() + "/" + MyApp.openIdent, ClipPathUtil.getAPPPath() + MyApp.openIdent);//复制文件夹到ClipPathUtil.getAPPPath()；
        MyLog.L(MString.SUCCESSED + "复制：ClipPathUtil()=" + ClipPathUtil.getAPPPath() + MyApp.openIdent);
        //copyFolder(from ,to);//复制文件夹到ClipPathUtil.getAPPPath()；
    }

    //读取
    public String getJson(String file) {
        return fileRead(getJsonFileName(file));
    }

    public List<ProjectItemBean> LoadFileData_ProjectItemBean(String file) {
        String json = fileRead(getJsonFileName(file));
        if (json != null && json.length() > 0) {
            return FastJsonUtil.JsonToGetProjectListBean(json);
        }
        return new ArrayList<>();
    }

    public ProjectItemBean LoadFileData_ProjectItem(String file) {
        String json = fileRead(getJsonFileName(file));
        if (json != null && json.length() > 0) {
            return FastJsonUtil.JsonToGetProject(json);
        }
        return null;
    }

    public List<SearchProjectBean> LoadFileData_SearchProjectBean(String file) {
        String json = fileRead(getJsonFileName(file));
        if (json != null && json.length() > 0) {
            return FastJsonUtil.JsonToGetSearchAllProject(json);
        }
        return new ArrayList<>();
    }

    public List<CategoryItemBean> LoadFileData_Category(String file) {
        String json = fileRead(getJsonFileName(file));
        if (json != null && json.length() > 0) {
            return FastJsonUtil.JsonToGetCategory(json);
        }
        return new ArrayList<>();
    }

    public List<EncyclopediaBean> LoadFileData_EncyclopediaBean(String file) {
        String json = fileRead(getJsonFileName(file));
        if (json != null && json.length() > 0) {
            return FastJsonUtil.JsonToGetEncyclopediaList(json);
        }
        return new ArrayList<>();
    }

    public List<EncyclopediaBean> LoadFileData_CollectList(String file) {
        String json = fileRead(getJsonFileName(file));
        if (json != null && json.length() > 0) {
            return FastJsonUtil.JsonToGetCollectList(json);
        }
        return new ArrayList<>();
    }


    public List<ExperienceBean> LoadFileData_ExperienceList(String file) {
        String json = fileRead(getJsonFileName(file));
        if (json != null && json.length() > 0) {
            return FastJsonUtil.getExperienceList(json);
        }
        return new ArrayList<>();
    }


    /**
     * 保存项目列表到缓存*
     */
    public boolean saveProjectList(String s) {
        boolean flag = false;
        ProjectItemBean b = FastJsonUtil.JsonToGetProject(s);
        String userid = MyApp.userInfo.getUser_id();
        if (userid.length() == 0 || (!b.getAuditor().contains(userid) && !b.getManager().contains(userid)
                && !b.getExplorationer().contains(userid) && !b.getDesigner().contains(userid))) {
            //权限不足
            return flag;
        }
        List<ProjectItemBean> data = GetFileUtil.getProjectStageListFile();

        if (data != null) {
            for (ProjectItemBean p : data) {
                if (MString.getValueId(p.getStage_id(), p.getUUID()).equals(MString.getValueId(b.getStage_id(), b.getUUID()))) {
                    data.remove(p);
                    break;
                }
            }
            data.add(0, b);
        } else {
            data = new ArrayList<>();
            data.add(b);
        }

        SetFileUtil.setProjectStageListFile(data);
        creatProjectFileByBaseInfo(b);
        try {

            FragmentUtil.getIntence(MyApp.activity).projectFragment.refreshhandler.sendEmptyMessage(1);
        } catch (Exception e) {
        }
        return true;
    }

    public boolean saveProjectList(ProjectItemBean b) {
        boolean flag = false;

        String userid = MyApp.userInfo.getUser_id();
        if (userid.length() == 0 || (!b.getAuditor().contains(userid) && !b.getManager().contains(userid)
                && !b.getExplorationer().contains(userid) && !b.getDesigner().contains(userid))) {
            //权限不足
            return flag;
        }
        List<ProjectItemBean> data = GetFileUtil.getProjectStageListFile();

        if (data != null) {
            for (ProjectItemBean p : data) {
                if (MString.getValueId(p.getStage_id(), p.getUUID()).equals(MString.getValueId(b.getStage_id(), b.getUUID()))) {
                    data.remove(p);
                    break;
                }
            }
            data.add(0, b);
        } else {
            data = new ArrayList<>();
            data.add(b);
        }

        SetFileUtil.setProjectStageListFile(data);
        creatProjectFileByBaseInfo(b);

        try {
            FragmentUtil.getIntence(MyApp.activity).projectFragment.refreshhandler.sendEmptyMessage(1);
        } catch (Exception e) {
        }
        return true;
    }

    public void creatProjectFileByBaseInfo(ProjectItemBean b) {
        JSONObject js = JSON.parseObject(JSON.toJSONString(b));
        Set<String> key = js.keySet();
        Map<String, Object> map = new HashMap<>();
        for (String k : key) {
            map.put(k, js.getString(k));
        }

        String Manager_name = getName("11", b.getManager());
        String Manager = b.getManager();

        String Explorationer_name = getName("12", b.getExplorationer());
        String Explorationer = b.getExplorationer();

        map.put(MString.manager, Manager_name);
        map.put(MString.manager_id, Manager);
        map.put(MString.explorationer, Explorationer_name);
        map.put(MString.explorationer_id, Explorationer);


        if (b.getUUID() != null && b.getUUID().length() > 0 && (b.getStage_id() == null || b.getStage_id().equals(MString.code_null) || b.getStage_id().equals(MString.code_zero))) {
            SetFileUtil.setProjectInfoN1(JSON.toJSONString(map), MString.getValueId(b.getStage_id(), b.getUUID()));
        } else {
            SetFileUtil.setProjectInfo(JSON.toJSONString(map), MString.getValueId(b.getStage_id(), b.getUUID()));
        }
    }

    public String getName(String type, String value) {
        String s = ShardPreferencesTool.getshare(MyApp.activity, MString.UserByTypeList + type, "");
        List<UserBean> unitUsersData = FastJsonUtil.JsonPersonnelData(s, type).get(0).getUnitsUser();
        String names = "";
        for (UserBean b : unitUsersData) {
            if ((b.getId() != null && value.contains(b.getId())) || value.contains(b.getID())) {
                names += b.getUsername() + ",";
            }
        }
        if (names.length() > 1) names = names.substring(0, names.length() - 1);
        return names;
    }

    public boolean saveProjectList(ProjectItemBean b, String s) {

        boolean flag = false;

        String userid = MyApp.userInfo.getUser_id();
        if (userid.length() == 0 || (!b.getAuditor().contains(userid) && !b.getManager().contains(userid)
                && !b.getExplorationer().contains(userid) && !b.getDesigner().contains(userid))) {
            //权限不足
            return flag;
        }
        List<ProjectItemBean> data = GetFileUtil.getProjectStageListFile();

        if (data != null) {
            for (ProjectItemBean p : data) {
                if (MString.getValueId(p.getStage_id(), p.getUUID()).equals(MString.getValueId(b.getStage_id(), b.getUUID()))) {
                    data.remove(p);
                    break;
                }
            }
            data.add(0, b);
        } else {
            data = new ArrayList<>();
            data.add(b);
        }

        SetFileUtil.setProjectStageListFile(data);
        if (s.length() > 0) {
            SetFileUtil.setProjectInfo(s, MString.getValueId(b.getStage_id(), b.getUUID()));
        }
        try {
            FragmentUtil.getIntence(MyApp.activity).projectFragment.refreshhandler.sendEmptyMessage(1);
        } catch (Exception e) {
        }
        return true;
    }


    /**
     * 移动*
     */

    void copyDBToSDcrad(String oldPath, String newPath) {
        copyFile(oldPath, newPath);
    }

    /**
     * 复制单个文件
     *
     * @param oldPath String 原文件路径 如：c:/fqf.txt
     * @param newPath String 复制后路径 如：f:/fqf.txt
     * @return boolean
     */
    public void copyFile(String oldPath, String newPath) {
        try {
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            if (oldfile.exists()) { //文件存在时
                InputStream inStream = new FileInputStream(oldPath); //读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1444];
                int length;
                while ((byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; //字节数 文件大小

                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
            }
        } catch (Exception e) {
            System.out.println("复制单个文件操作出错");
            e.printStackTrace();

        }

    }

    public void copyFile(File oldfile, String newPath) {
        try {
            int bytesum = 0;
            int byteread = 0;
            http:
//192.168.1.132:80/upload/filetemp/ProjectStage_4143.zip
            if (oldfile.exists()) { //文件存在时
                InputStream inStream = new FileInputStream(oldfile.getPath()); //读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1444];
                int length;
                while ((byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; //字节数 文件大小

                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
            }
        } catch (Exception e) {
            System.out.println("复制单个文件操作出错");
            e.printStackTrace();

        }

    }

    /**
     * 复制整个文件夹内容
     *
     * @param oldPath String 原文件路径 如：c:/fqf
     * @param newPath String 复制后路径 如：f:/fqf/ff
     * @return boolean
     */
    public void copyFolder(String oldPath, String newPath) {

        try {
            (new File(newPath)).mkdirs(); //如果文件夹不存在 则建立新文件夹
            File a = new File(oldPath);
            String[] file = a.list();
            File temp = null;
            if (file == null) return;
            for (int i = 0; i < file.length; i++) {
                if (oldPath.endsWith(File.separator)) {
                    temp = new File(oldPath + file[i]);
                } else {
                    temp = new File(oldPath + File.separator + file[i]);
                }

                if (temp.isFile()) {
                    FileInputStream input = new FileInputStream(temp);
                    FileOutputStream output = new FileOutputStream(newPath + "/" +
                            (temp.getName()).toString());
                    byte[] b = new byte[1024 * 5];
                    int len;
                    while ((len = input.read(b)) != -1) {
                        output.write(b, 0, len);
                    }
                    output.flush();
                    output.close();
                    input.close();
                }
                if (temp.isDirectory()) {//如果是子文件夹
                    copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i]);
                }
            }
        } catch (Exception e) {
            System.out.println("复制整个文件夹内容操作出错");
            e.printStackTrace();

        }

    }


    public void copyCoverFolder(String oldPath, String newPath, String uuid) {

        try {


            File filen = new File(newPath);
            if (!filen.exists()) {
                filen.mkdirs(); //如果文件夹不存在 则建立新文件夹
            }
            File a = new File(oldPath);
            String[] file = a.list();
            File temp = null;
            for (int i = 0; i < file.length; i++) {
                if (file[i].toLowerCase().contains(uuid.toLowerCase())) {
                    String oldfile = "";
                    if (oldPath.endsWith(File.separator)) {
                        oldfile = oldPath + file[i];
                    } else {
                        oldfile = oldPath + File.separator + file[i];
                    }
                    temp = new File(oldfile);

                    if (temp.isFile()) {
                        String newpath = newPath + "/" + (temp.getName()).toString();
                        File newfile = new File(newPath);
                        if (newfile.exists()) {
                            //覆盖合并
                            newfile.delete();
                            saveFile(temp, newpath);
                        } else {
                            saveFile(temp, newpath);//复制过来
                        }

                    }
                    if (temp.isDirectory()) {//如果是子文件夹
                        copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i]);
                    }
                }

            }
        } catch (Exception e) {
            System.out.println("复制整个文件夹内容操作出错");
            e.printStackTrace();

        }

    }

    public void copyCoverFolderByNoFtilter(String oldPath, String newPath, String uuid) {

        try {


            File filen = new File(newPath);
            if (!filen.exists()) {
                filen.mkdirs(); //如果文件夹不存在 则建立新文件夹
            }
            File a = new File(oldPath);
            String[] file = a.list();
            File temp = null;
            for (int i = 0; i < file.length; i++) {

                String oldfile = "";
                if (oldPath.endsWith(File.separator)) {
                    oldfile = oldPath + file[i];
                } else {
                    oldfile = oldPath + File.separator + file[i];
                }
                temp = new File(oldfile);

                if (temp.isFile()) {
                    String newpath = newPath + "/" + (temp.getName()).toString();
                    File newfile = new File(newPath);
                    if (newfile.exists()) {
                        //覆盖合并
                        newfile.delete();
                        saveFile(temp, newpath);
                    } else {
                        saveFile(temp, newpath);//复制过来
                    }

                }
                if (temp.isDirectory()) {//如果是子文件夹
                    copyCoverFolderByNoFtilter(oldPath + "/" + file[i], newPath + "/" + file[i], uuid);
                }
            }
        } catch (Exception e) {
            System.out.println("复制整个文件夹内容操作出错");
            e.printStackTrace();

        }

    }

    public void saveFile(String temp, String newpath) {
        try {
            FileInputStream input = new FileInputStream(temp);
            FileOutputStream output = new FileOutputStream(newpath);
            byte[] b = new byte[1024 * 5];
            int len;
            while ((len = input.read(b)) != -1) {
                output.write(b, 0, len);
            }
            output.flush();
            output.close();
            input.close();
        } catch (Exception e) {
            System.out.println("复制整个文件夹内容操作出错");
            e.printStackTrace();

        }
    }

    public void saveFile(File temp, String newpath) {
        try {
            FileInputStream input = new FileInputStream(temp);
            FileOutputStream output = new FileOutputStream(newpath);
            byte[] b = new byte[1024 * 5];
            int len;
            while ((len = input.read(b)) != -1) {
                output.write(b, 0, len);
            }
            output.flush();
            output.close();
            input.close();
        } catch (Exception e) {
            System.out.println("复制整个文件夹内容操作出错");
            e.printStackTrace();

        }
    }

    /**
     * 覆盖项目文件时备份图片文件*
     */
    public void copyFolderPhotos(String oldPath, String newPath, String id) {
        try {
            String stageid = id.replace(MString.Project_, "");

            (new File(newPath)).mkdirs(); //如果文件夹不存在 则建立新文件夹
            File a = new File(oldPath);
            String[] file = a.list();
            File temp = null;
            for (int i = 0; i < file.length; i++) {
                if (oldPath.endsWith(File.separator)) {
                    temp = new File(oldPath + file[i]);
                } else {
                    temp = new File(oldPath + File.separator + file[i]);
                }

                if (temp.isDirectory()) { //如果是子文件夹
                    copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i]);
                }
            }
        } catch (Exception e) {
            MyLog.E("复制整个文件夹内容操作出错");
            e.printStackTrace();
        }

    }

    public void copyFolderPhotos(String oldPath, String newPath) {
        try {
            (new File(newPath)).mkdirs(); //如果文件夹不存在 则建立新文件夹
            File a = new File(oldPath);
            String[] file = a.list();
            File temp = null;
            if (file == null) return;
            for (int i = 0; i < file.length; i++) {
                if (oldPath.endsWith(File.separator)) {
                    temp = new File(oldPath + file[i]);
                } else {
                    temp = new File(oldPath + File.separator + file[i]);
                }

                if (temp.isDirectory()) { //如果是子文件夹
                    copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i]);
                }
            }
        } catch (Exception e) {
            System.out.println("复制整个文件夹内容操作出错");
            e.printStackTrace();
        }

    }

    /**
     * 将图片文件移动到项目文件中*
     */
    void copyFolderToPhotos(String oldPath, String newPath) {
        try {
            (new File(newPath)).mkdirs(); //如果文件夹不存在 则建立新文件夹
            File a = new File(oldPath);
            String[] file = a.list();
            File temp = null;
            for (int i = 0; i < file.length; i++) {
                if (oldPath.endsWith(File.separator)) {
                    temp = new File(oldPath + file[i]);
                } else {
                    temp = new File(oldPath + File.separator + file[i]);
                }

                if (temp.isDirectory()) { //如果是子文件夹
                    copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i]);
                }
            }
        } catch (Exception e) {
            System.out.println("复制整个文件夹内容操作出错");
            e.printStackTrace();
        }

    }

    /**
     * 删除*
     */
    public void delect(String path) {
        MyLog.L(MString.SUCCESSED + " 删除path==" + path);
        File f = new File(path);
        if (f.exists()) delete(f);
    }

    public void delect(String name, String filename) {
        String PATH = mContext.getFilesDir().getPath() + File.separator + MyApp.openIdent + File.separator + MString.Project_ + name + File.separator + filename;
        delect(PATH);
    }

    public void delectr(String name, String filename) {
        String PATH = mContext.getFilesDir().getPath() + File.separator + MyApp.openIdent + File.separator + MString.Request + File.separator + MString.Project_ + name + File.separator + filename;
        delect(PATH);
    }

    public void delete(File file) {
        if (file.isFile()) {
            file.delete();
            return;
        }

        if (file.isDirectory()) {
            File[] childFiles = file.listFiles();
            if (childFiles == null || childFiles.length == 0) {
                file.delete();
                return;
            }

            for (int i = 0; i < childFiles.length; i++) {
                delete(childFiles[i]);
            }
            file.delete();
        }
    }


    /**
     * 存储路径*
     */
    public String getSDPath(String name) {
        return ClipPathUtil.getAPPPath() + name;
    }

    public String getSystemPath(String name) {
        return mContext.getFilesDir().getPath() + File.separator + name;
    }


    private boolean deleteLastFromFloder(String path) {
        boolean success = false;
        try {
            ArrayList<File> images = new ArrayList<File>();
            getFiles(images, path);
            File latestSavedImage = images.get(0);
            if (latestSavedImage.exists()) {
                for (int i = 1; i < images.size(); i++) {
                    File nextFile = images.get(i);
                    if (nextFile.lastModified() > latestSavedImage.lastModified()) {
                        latestSavedImage = nextFile;

                    }

                }

                MyLog.L("brady mimages = " + latestSavedImage.getAbsolutePath());
                success = latestSavedImage.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return success;
    }

    private static void getFiles(ArrayList<File> fileList, String path) {
        File nfile = new File(path);
        if (!nfile.exists()) {
            nfile.mkdirs();
        }
        File[] allFiles = nfile.listFiles();
        for (int i = 0; i < allFiles.length; i++) {
            File file = allFiles[i];
            if (file.isFile()) {
                fileList.add(file);
            }
//            else if (!file.getAbsolutePath().contains(".thumnail")) {
//                getFiles(fileList, file.getAbsolutePath());
//            }
        }
    }


    public static List<BackPhoto_Bean> addPhotos(String path, String type) {
        List<BackPhoto_Bean> bean = new ArrayList<>();
        try {
            path += type;
            ArrayList<File> images = new ArrayList<File>();
            getFiles(images, path);
            File latestSavedImage = images.get(0);
            if (latestSavedImage.exists()) {
                //方法
                for (File f : images) {
                    BackPhoto_Bean photo_bean = new BackPhoto_Bean();
                    photo_bean.setPhoto_thumb(f.getPath());
                    photo_bean.setPhoto_url(f.getName());
                    photo_bean.setPhoto_type(type);
                    photo_bean.setPhoto_id("");
                    photo_bean.setUuid(MString.getMyUUID());
                    bean.add(photo_bean);
                    MyLog.L(MString.SUCCESSED + "  path=" + f.getPath());
                    MyLog.L(MString.SUCCESSED + "  path=" + f.getName());
                }
            } else {
                MyLog.L(MString.SUCCESSED + "  path=" + path);
            }
        } catch (Exception e) {
        }
        return bean;
    }


    /**
     * 删除单个文件
     *
     * @param filePath 被删除文件的文件名
     * @return 文件删除成功返回true，否则返回false
     */
    public static boolean deleteFile(String filePath) {
        File file = new File(filePath);
        if (file.isFile() && file.exists()) {
            return file.delete();
        }
        return false;
    }

    /**
     * 删除文件夹以及目录下的文件
     *
     * @param filePath 被删除目录的文件路径
     * @return 目录删除成功返回true，否则返回false
     */
    public static boolean deleteDirectory(String filePath) {
        boolean flag = false;
        //如果filePath不以文件分隔符结尾，自动添加文件分隔符
        if (!filePath.endsWith(File.separator)) {
            filePath = filePath + File.separator;
        }
        File dirFile = new File(filePath);
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            return false;
        }
        flag = true;
        File[] files = dirFile.listFiles();
        //遍历删除文件夹下的所有文件(包括子目录)
        for (int i = 0; i < files.length; i++) {
            if (files[i].isFile()) {
                //删除子文件
                flag = deleteFile(files[i].getAbsolutePath());
                if (!flag) break;
            } else {
                //删除子目录
                flag = deleteDirectory(files[i].getAbsolutePath());
                if (!flag) break;
            }
        }
        if (!flag) return false;
        //删除当前空目录
        return dirFile.delete();
    }

    /**
     * 根据路径删除指定的目录或文件，无论存在与否
     *
     * @param filePath 要删除的目录或文件
     * @return 删除成功返回 true，否则返回 false。
     */
    public static boolean DeleteFolder(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            return false;
        } else {
            if (file.isFile()) {
                // 为文件时调用删除文件方法
                return deleteFile(filePath);
            } else {
                // 为目录时调用删除目录方法
                return deleteDirectory(filePath);
            }
        }
    }

    /**
     * 判断文件夹下的文件是否存在
     *
     * @param f 文件夹流
     * @return 文件有返回true，否则返回false
     */
    public static boolean checkFile(File f) {

        boolean flag = false;
        if (f.exists()) {
            File[] allFiles = f.listFiles();
            if (allFiles.length > 0) {
                for (int i = 0; i < allFiles.length; i++) {
                    if (allFiles[i].isFile()) {
                        return true;
                    } else {
                        flag = checkFile(new File(allFiles[i].getAbsolutePath()));
                    }
                }
            } else {
                return false;
            }
        }
        return flag;
    }
}
